﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Medicalsystem.MCP.FormDesigner.Common;

namespace Medicalsystem.MCP.FormDesigner.Ctl
{
    /// <summary>
    /// 自定义属性展示控件
    /// </summary>
    //[ToolboxItem(false)]
    public partial class ctl_PropertyGrid : DevExpress.XtraEditors.XtraUserControl
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="control"></param>
        public delegate void DesignHandler(System.Windows.Forms.Control control);

        /// <summary>
        /// 外部事件 用于设计器上控件焦点的改变
        /// </summary>
        public event DesignHandler DesignEvent;

        /// <summary>
        /// 按键的X坐标
        /// </summary>
        private int Point_X;

        private bool _eventAvail = false;

        //执行comboBox_SubControl_SelectedIndexChanged事件时刷新了设计容器
        //触发了MyPropertyGrid_Leave事件（此时不需要触发该事件） 用一个开关控制事件的执行
        private bool _leaveEventAvail = true;

        private int _width = 0; //控件的可用最大宽度
        private int _offset = 100; //收缩偏移量
        private bool _visible = false; //用于收缩控制

        private Timer checkTimer = new Timer();    //定时器

        /// <summary>
        /// 自定义属性展示控件
        /// </summary>
        public ctl_PropertyGrid()
        {
            InitializeComponent();

            _width = this.Width;
            checkTimer.Interval = 50;
            checkTimer.Tick += new EventHandler(checkTimer_Tick);
            checkTimer.Stop();
        }

        ///// <summary>
        ///// 当前选取的控件-容器中的焦点控件
        ///// </summary>
        //public System.Windows.Forms.Control SelectControl
        //{
        //    get
        //    {
        //        if (this.comboBox_SubControl.SelectedItem != null)
        //        {
        //            return ((ControlItem<System.Windows.Forms.Control>)this.comboBox_SubControl.SelectedItem).Object;
        //        }
        //        else
        //        {
        //            return null;
        //        }
        //    }
        //}

        /// <summary>
        /// 添加控件选项
        /// </summary>
        public void Add(System.Windows.Forms.Control control)
        {
            try
            {
                if ((control is Medicalsystem.MCP.FormDesigner.Interface.ICtrlBase) && !(control as Medicalsystem.MCP.FormDesigner.Interface.ICtrlBase).PropertyObject.PropertyChangeEventBind)
                {
                    (control as Medicalsystem.MCP.FormDesigner.Interface.ICtrlBase).PropertyObject.PropertyChangeEvent += new Medicalsystem.MCP.FormDesigner.Property.GetCtrlProperty.PropertyHandler(PropertyObject_PropertyChangeEvent);
                }

                this.comboBox_SubControl.Properties.Items.Add(new ControlItem<System.Windows.Forms.Control>(control, string.Format("{0} - {1}", control.Name, control.GetType().ToString())));
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误", ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); ;
            }
        }

        /// <summary>
        /// 删除控件选项
        /// </summary>
        public void Clear()
        {
            this.comboBox_SubControl.Properties.Items.Clear();
            this.MypropertyGrid.SelectedObject = null;
        }

        /// <summary>
        /// 设置焦点控件属性
        /// </summary>
        /// <param name="control"></param>
        public void SelectedObject(System.Windows.Forms.Control control)
        {
            try
            {
                ComboBoxSelectedItem(control);
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误", ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); ;
            }
        }

        /// <summary>
        /// 模板属性获取 - 外部调用
        /// </summary>
        public object SelectedForm
        {
            set
            {
                this.MypropertyGrid.SelectedObject = value;
                _eventAvail = false;
                this.comboBox_SubControl.SelectedIndex = 0;
                _eventAvail = true;
            }
        }

        /// <summary>
        /// 是否显示控件
        /// </summary>
        [Browsable(false)]
        public bool VisibleCustom
        {
            get
            {
                return this.Visible;
            }
            set
            {
                _visible = value;

                //显示
                if (_visible && !this.Visible)
                {
                    this.Width = 1;
                    this.Visible = true;
                    this.checkTimer.Start();
                }
                else if (!_visible && this.Visible)
                {
                    _width = this.Width;
                    this.checkTimer.Start();
                }
            }
        }

        #region 私有方法

        /// <summary>
        /// 属性改变响应 -- 此处用于控件名称改变处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        private void PropertyObject_PropertyChangeEvent(Object sender, string propertyName, Object value)
        {
            if (propertyName.Equals("Name"))
            {
                this.comboBox_SubControl.Properties.Items.RemoveAt(this.comboBox_SubControl.SelectedIndex);
                System.Windows.Forms.Control control = (System.Windows.Forms.Control)sender;
                ControlItem<System.Windows.Forms.Control> ci = new ControlItem<System.Windows.Forms.Control>(control, string.Format("{0} - {1}", control.Name, control.GetType().ToString()));
                this.comboBox_SubControl.Properties.Items.Add(ci);
                _eventAvail = false;
                this.comboBox_SubControl.SelectedItem = ci;
                _eventAvail = true;
            }
        }

        /// <summary>
        /// 收缩控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkTimer_Tick(object sender, EventArgs e)
        {
            //显示
            if (_visible)
            {
                if (_width < (this.Width + _offset))
                {
                    this.Width = _width;
                    this.checkTimer.Stop();
                    this.Refresh();
                }
                else
                {
                    this.Width += _offset;
                }
            }
            else
            {
                if (this.Width - _offset <= 0)
                {
                    this.checkTimer.Stop();
                    this.Visible = false;
                }
                else
                {
                    this.Width -= _offset;
                }
            }
        }

        /// <summary>
        /// 显示选取项
        /// </summary>
        private void ComboBoxSelectedItem(System.Windows.Forms.Control control)
        {
            //防止此处执行ComboBoxSelectedIndexChange事件
            _eventAvail = false;

            if (control != null)
            {
                if (this.comboBox_SubControl.SelectedItem != null && (this.comboBox_SubControl.SelectedItem as ControlItem<System.Windows.Forms.Control>).Object == control)
                {
                    PropertyGridSelectedItem(control);
                }
                else
                {
                    foreach (ControlItem<System.Windows.Forms.Control> CI in this.comboBox_SubControl.Properties.Items)
                    {
                        if (CI.Object == control)
                        {
                            this.comboBox_SubControl.SelectedItem = CI;
                            PropertyGridSelectedItem(control);
                            break;
                        }
                    }
                }
            }
            else
            {
                this.comboBox_SubControl.SelectedIndex = -1;
                PropertyGridSelectedItem(null);
            }

            this.Refresh();

            _eventAvail = true;
        }

        /// <summary>
        /// 获取或设置在网格中显示属性的对象
        /// </summary>
        private void PropertyGridSelectedItem(System.Windows.Forms.Control control)
        {
            if (control is Medicalsystem.MCP.FormDesigner.Interface.ICtrlBase)
            {
                this.MypropertyGrid.SelectedObject = (control as Medicalsystem.MCP.FormDesigner.Interface.ICtrlBase).PropertyObject;
            }
            else if (control is Form)
            {
                //模板赋值转到外部
                OnDesignEvent(control);
            }
        }

        /// <summary>
        /// 改变下拉框选项时需要设置设计器控件焦点（调用外部事件执行）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_SubControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_eventAvail)
            {
                _leaveEventAvail = false;

                if (this.comboBox_SubControl.SelectedItem.ToString() == "")
                {
                    PropertyGridSelectedItem(null);

                }
                else if (this.comboBox_SubControl.SelectedItem != null)
                {
                    //PropertyGridSelectedItem((this.comboBox_SubControl.SelectedItem as ControlItem<System.Windows.Forms.Control>).Object);
                    OnDesignEvent((this.comboBox_SubControl.SelectedItem as ControlItem<System.Windows.Forms.Control>).Object);
                }
                else
                {
                    PropertyGridSelectedItem(null);
                }

                _leaveEventAvail = true;
                this.Focus(); //操作控件时保持控件焦点不外移（OnDesignEvent 方法会将焦点外移）
            }
        }

        /// <summary>
        /// 执行外部事件
        /// </summary>
        private void OnDesignEvent(System.Windows.Forms.Control control)
        {
            if (DesignEvent != null)
            {
                DesignEvent(control);
            }
        }

        private void ctl_HeaderClose1_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void pal_Left_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point_X = System.Windows.Forms.Control.MousePosition.X;
            }
        }

        private void pal_Left_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePos = System.Windows.Forms.Control.MousePosition;
                this.Width = this.Width - (mousePos.X - Point_X);
                Point_X = mousePos.X;
                this._width = this.Width;
                this.Refresh();
            }
        }

        #endregion 私有方法
    }
}